package com.myfojing.mycloud;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class ConfigDdnsFragment extends Fragment {
    private static final String ARG_PARAM1 = "ip";
    private static final String ARG_PARAM2 = "port";

    private String ip;
    private String port;

    private Spinner spinner_domain;
    private EditText txt_ddns_host;
    private EditText txt_ddns_user;
    private EditText txt_ddns_password;
    private Button btnSave;
    private Spinner spinner_interval;

    private Sensirion sensirion;
    private Handler handler;

    private OnFragmentInteractionListener mListener;

    public ConfigDdnsFragment() {
        // Required empty public constructor
    }

    public static ConfigDdnsFragment newInstance(String param1, String param2) {
        ConfigDdnsFragment fragment = new ConfigDdnsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ip = getArguments().getString(ARG_PARAM1);
            port = getArguments().getString(ARG_PARAM2);
            sensirion = new Sensirion(ip, port);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_config_ddns, container, false);
        handler = new Handler();
        // ui
        spinner_domain = (Spinner) view.findViewById(R.id.ddns_domain);
        String[] domains = getResources().getStringArray(R.array.domains);
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(view.getContext(),
                android.R.layout.simple_spinner_item, domains);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_domain.setAdapter(adapter);

        txt_ddns_host = (EditText) view.findViewById(R.id.txt_ddns_host);
        txt_ddns_user = (EditText) view.findViewById(R.id.txt_ddns_user);
        txt_ddns_password = (EditText) view.findViewById(R.id.txt_ddns_pwd);

        spinner_interval = (Spinner) view.findViewById(R.id.ddns_update_interval);
        List<Obj_interval> list = new ArrayList<>();
        list.add(new Obj_interval("1分钟", 60 * 1000));
        list.add(new Obj_interval("10分钟", 600 * 1000));
        list.add(new Obj_interval("1小时", 3600 * 1000));
        final MyAdapter adapter_2 = new MyAdapter(view.getContext(), list);
        spinner_interval.setAdapter(adapter_2);
        adapter_2.notifyDataSetChanged();

        btnSave = (Button) view.findViewById(R.id.ddns_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sensirion != null) {
                    JSONObject object = new JSONObject();
                    try {
                        object.put("host", txt_ddns_host.getText().toString());
                        object.put("domain", spinner_domain.getSelectedItem().toString());
                        object.put("user", txt_ddns_user.getText().toString());
                        object.put("password", txt_ddns_password.getText().toString());
                        object.put("interval", ((Obj_interval)spinner_interval.getSelectedItem()).getInterval());
                        sensirion.write("write_ddns", object.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        sensirion.setSensirionListener(new Sensirion.SensirionListener() {
            @Override
            public void onDataReady(JSONObject data) {
                try {
                    // 写
                    if (data.getString("cmd").equals("write_ddns")) {
                        if (data.getBoolean("success")) {
                            Snackbar.make(view, "写ddns成功", Snackbar.LENGTH_LONG).show();
                        } else {
                            Snackbar.make(view, "写ddns失败", Snackbar.LENGTH_LONG).show();
                        }
                    }
                    // 读
                    if (data.getString("cmd").equals("read_ddns")) {
                        final String host = data.getString("host");
                        final String user = data.getString("user");
                        final String password = data.getString("password");
                        final String domain = data.getString("domain");
                        final long interval = data.getLong("interval");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                txt_ddns_host.setText(host);
                                txt_ddns_user.setText(user);
                                txt_ddns_password.setText(password);
                                spinner_domain.setSelection(adapter.getPosition(domain));
                                spinner_interval.setSelection(adapter_2.getPosition(interval));
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        // read default
        sensirion.read("read_ddns");
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    // 间隔对象
    private class Obj_interval {
        private String name;
        private int interval;

        public Obj_interval(String name, int interval) {
            this.name = name;
            this.interval = interval;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getInterval() {
            return interval;
        }

        public void setInterval(int interval) {
            this.interval = interval;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    private class MyAdapter extends BaseAdapter {
        private Context context;
        private List<Obj_interval> list;

        @Override
        public int getCount() {
            return list.size();
        }

        public MyAdapter(Context context, List<Obj_interval> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(context);
            ViewHolder viewHolder;

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.spinner_adapter, null);
                viewHolder = new ViewHolder();
                viewHolder.txt_interval = (TextView) convertView.findViewById(R.id.apinner_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.txt_interval.setText(getItem(position).toString());

            return convertView;
        }

        private class ViewHolder {
            TextView txt_interval;
        }

        public int getPosition(Long v) {
            int len = getCount();
            int i = 0;
            for (;i<len;i++) {
                if (list.get(i).getInterval() == v)
                    break;;
            }
            return i;
        }

    }

    // end
}
